# 声明一个蓝图
import os
from flask import Blueprint, request
import requests

from controllers import R


third_party_callback = Blueprint(
    "third_party_callback", __name__, url_prefix="/thirdParty"
)


@third_party_callback.route("/checkStarred", methods=["POST"])
def check_starred():
    """
    校验是否点亮项目
    :return:
    """
    code = request.json.get("code")
    redirect_uri = os.environ.get(
        "GITEE_REDIRECT_URI", "https://flow-py.mldong.com/oauth/gitee"
    )
    client_id = os.environ.get("GITEE_CLIENT_ID", "your_gitee_client_id_here")
    client_secret = os.environ.get(
        "GITEE_CLIENT_SECRET", "your_gitee_client_secret_here"
    )

    token_api_url = f"https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}"
    response = requests.post(token_api_url)
    access_token = response.json().get("access_token")

    owner = os.environ.get("GITEE_OWNER", "mldong666")
    repo = os.environ.get("GITEE_REPO", "mldong-python")
    check_url = f"https://gitee.com/api/v5/user/starred/{owner}/{repo}?access_token={access_token}"

    try:
        response = requests.get(check_url)
        if response.status_code == 200 or response.status_code == 204:

            return R.data({"flag": True})
        else:
            return R.data({"flag": False})
    except Exception:
        return R.data({"flag": False})
